package com.nova.android.tvlauncher.ui.fragment.atv

import android.content.res.Resources
import android.os.Bundle
import android.view.KeyEvent
import android.view.View
import android.view.animation.DecelerateInterpolator
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.constraintlayout.widget.ConstraintSet
import androidx.core.view.isVisible
import androidx.lifecycle.lifecycleScope
import androidx.transition.ChangeBounds
import androidx.transition.Transition
import androidx.transition.TransitionManager
import com.nova.android.tvlauncher.BuildConfig
import com.nova.android.tvlauncher.R
import com.nova.android.tvlauncher.bean.atv_bean.HomeBannerAtvDto
import com.nova.android.tvlauncher.databinding.FragmentAppsAtvBinding
import com.nova.android.tvlauncher.ext.setTextWithSlideHorizontal
import com.nova.android.tvlauncher.net.UrlManager
import io.github.lib_autorun.net.NetworkHelper
import io.github.lib_autorun.net.enum.RequestMethod
import com.nova.android.tvlauncher.databinding.FragmentAppsAtvXintuBinding
import com_github_lib_base.base.BaseVMFragment
import com_github_lib_base.base.BaseViewModel
import com_github_lib_base.ext.clickNoRepeat
import com_github_lib_base.ext.openApp
import com_github_lib_base.ext.replaceChildFragment
import com_github_lib_base.ext.stringValue
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch

class AppsAtvXintuFragment : BaseVMFragment<FragmentAppsAtvXintuBinding, BaseViewModel>() {


    // 在类顶部添加动画工具函数M
    private fun fadeView(view: View, show: Boolean, duration: Long = 300) {
        view.clearAnimation()
        val animator = if (show) {
            view.alpha = 0f
            view.isVisible = true
            view.animate().alpha(1f).setDuration(duration)
        } else {
            view.animate().alpha(0f).setDuration(duration).withEndAction {
                view.isVisible = false
            }
        }
        animator.start()
    }

    fun showTopView(){
        (parentFragment as MainATVXintuFragment).showTopView()
        //fadeView(mBind.vpBanner,true)
        fadeView(mBind.tvAppsBannerTitle,true)
        fadeView(mBind.subtitle,true)
        fadeView(mBind.description,true)
        //mBind.vpBanner.isVisible = true
        //mBind.tvHomeBannerTitle.isVisible = true
        //mBind.subtitle.isVisible = true
        //mBind.description.isVisible = true
    }
    fun hideTopView(){
        (parentFragment as MainATVXintuFragment).hideTopView()
        fadeView(mBind.vpBanner,false)
        fadeView(mBind.tvAppsBannerTitle,false)
        fadeView(mBind.subtitle,false)
        fadeView(mBind.description,false)
        //mBind.vpBanner.isVisible = false
        //mBind.tvHomeBannerTitle.isVisible = false
        //mBind.subtitle.isVisible = false
        //mBind.description.isVisible = false
    }

    private var showBigPicJob: Job? = null
    private var delayTime: Long = 3000L // 延迟时间，300ms 可以根据需求调整
    private fun delayShowBigPic(isCancle:Boolean = false) {
        if(!isCancle){
            // 清除上一次的 Fragment 加载任务
            showBigPicJob?.cancel()
            // 启动一个新的延迟任务来加载 Fragment
            showBigPicJob = lifecycleScope.launch {
                delay(delayTime)
                //setListFragmentHalfHeight()
                updateLayoutPercentages(2)
                setListFragmentLittleHeight(true)
                changeTextViewTopConstraint(true)
            }
        }else{
            showBigPicJob?.cancel()
        }


    }

    var isFirst = true

    private var focusChangeJob: Job? = null
    private val FOCUS_DELAY = 100L // 延迟 100ms 确保执行最后状态
    override fun initView() {

        replaceChildFragment(AppListAtvXintuFragment.newInstance(),R.id.apps_fragment)

        mBind.tvAppsBannerTitle.setOnFocusChangeListener { _, hasFocus ->
            focusChangeJob?.cancel() // 取消旧的延迟任务
            focusChangeJob = lifecycleScope.launch {
                delay(FOCUS_DELAY) // 延迟执行，确保最后状态
                if(hasFocus){
                    mBind.tvOpen.isVisible = true
                    mBind.dotsIndicator.isVisible = true
                    setListFragmentHalfHeight()
                    updateLayoutPercentages(1)
                    delayShowBigPic()
                }else{
                    changeTextViewTopConstraint(false)
                    mBind.tvOpen.isVisible = false
                    mBind.dotsIndicator.isVisible = false
                    updateLayoutPercentages(0)
                    setListFragmentFullHeight(false)
                    delayShowBigPic(true)
                }
            }
        }


        mBind.tvAppsBannerTitle.clickNoRepeat {
            val packageName = "com.android.vending"
            packageName.openApp()
            //curBannerPackageName?.let { it.openApp() }
        }


        mBind.tvAppsBannerTitle.setOnKeyListener { _, keyCode, event ->
            if (event.action == KeyEvent.ACTION_DOWN) {
                when (keyCode) {
                    KeyEvent.KEYCODE_DPAD_DOWN -> {
                        mBind.tvOpen.isVisible = false
                        mBind.dotsIndicator.isVisible = false
                        changeTextViewTopConstraint(false)
                        updateLayoutPercentages(0)
                        setListFragmentFullHeight(false)
                        delayShowBigPic(true)
                        val childFragment = childFragmentManager.findFragmentById(R.id.apps_fragment) as? AppListAtvXintuFragment

                        childFragment?.let {
                            if (it.isAdded) { // 确保 Fragment 已附加
                                it.reqGetFocus() // 调用子 Fragment 的方法
                            }
                        }
                        return@setOnKeyListener true
                    }
                    KeyEvent.KEYCODE_DPAD_LEFT -> {
                        mBind.vpBanner.previousPage()
                        return@setOnKeyListener true
                    }
                    KeyEvent.KEYCODE_DPAD_RIGHT -> {
                        mBind.vpBanner.nextPage()
                        return@setOnKeyListener true
                    }
                    else -> return@setOnKeyListener false
                }

            }else return@setOnKeyListener false
        }

       // getBanner()

        mBind.vpBanner.apply {
            setImages(
                arrayListOf(
                    HomeBannerAtvDto(bannerRes = R.drawable.banner_googlepaly)
                )
            )
            startAutoScroll()
        }

        mBind.dotsIndicator.attachTo(mBind.vpBanner.viewPager)

        mBind.vpBanner.onPageSelected {
           // curBannerPackageName = bannerList?.get(it)?.package_name.toString()
            mBind.tvAppsBannerTitle.setTextWithSlideHorizontal(com.nova.lib_lang.R.string.main_apps_txt_4.stringValue())
            mBind.subtitle.setTextWithSlideHorizontal(com.nova.lib_lang.R.string.main_apps_txt_5.stringValue())
            mBind.description.setTextWithSlideHorizontal(com.nova.lib_lang.R.string.main_apps_txt_7.stringValue())
            mBind.tvOpen.setTextWithSlideHorizontal(com.nova.lib_lang.R.string.main_apps_txt_6.stringValue())
        }




    }

    var bannerList :List<HomeBannerAtvDto>?=null
    var curBannerPackageName:String ?=null
    private fun getBanner() {
        NetworkHelper.makeRequest(
            UrlManager.BANNER_HOME,
            RequestMethod.POST,
            mapOf(
                "req_id" to 0,
                "channel" to BuildConfig.CHANNEL,
                "lang" to "en",
                "launch_type" to 1,
                "req_from" to 2,
            ),
        ) { dto: List<HomeBannerAtvDto>?, error: Throwable? ->
            if (error == null) {

                dto?.let {
                    bannerList = dto
                    val list = dto.map { it.app_img ?: "" }
                    mBind.vpBanner.apply {
                        setImages(
                            arrayListOf(HomeBannerAtvDto(bannerRes = R.drawable.banner_googlepaly))
                        )
                        startAutoScroll()
                    }

                    mBind.dotsIndicator.attachTo(mBind.vpBanner.viewPager)

                }

            } else {
            }
        }

    }

    fun setBannerfocuable(){
        mBind.tvAppsBannerTitle.isFocusable = true
        mBind.tvAppsBannerTitle.isFocusableInTouchMode = true
    }

   // private var lastExecutionTime = 0L
    //private  val DEBOUNCE_INTERVAL = 300L // 300ms 防抖间隔

    fun setListFragmentFullHeight(
        full: Boolean,
        animate: Boolean = true,
    ) {
        if (!isFirst) {
            val constraintLayout = mBind.appsFragment.parent as ConstraintLayout
            val constraintSet = ConstraintSet().apply {
                clone(constraintLayout)
                if (full) {
                    clear(R.id.apps_fragment, ConstraintSet.TOP)
                    connect(
                        R.id.apps_fragment, ConstraintSet.TOP,
                        ConstraintSet.PARENT_ID, ConstraintSet.TOP,
                        0
                    )
                    constrainHeight(R.id.apps_fragment, Resources.getSystem().displayMetrics.heightPixels)
                } else {
                    clear(R.id.apps_fragment, ConstraintSet.TOP)
                    connect(
                        R.id.apps_fragment, ConstraintSet.TOP,
                        R.id.guideline_center, ConstraintSet.BOTTOM,
                        0
                    )
                    constrainHeight(R.id.apps_fragment, ConstraintSet.MATCH_CONSTRAINT)
                }
            }

            if (animate) {
                val transition = ChangeBounds().apply {
                    duration = 300
                    interpolator = DecelerateInterpolator()
                }

                TransitionManager.beginDelayedTransition(constraintLayout, transition)
                constraintSet.applyTo(constraintLayout)

            } else {
                constraintSet.applyTo(constraintLayout)
            }
        } else {
            isFirst = false
        }
    }

    fun setListFragmentHalfHeight(animate: Boolean = true) {
        val constraintLayout = mBind.appsFragment.parent as ConstraintLayout
        val constraintSet = ConstraintSet().apply {
            clone(constraintLayout) // 克隆当前约束状态
            clear(R.id.apps_fragment, ConstraintSet.TOP) // 清除原有顶部约束
            connect(
                R.id.apps_fragment, ConstraintSet.TOP,
                R.id.guideline_50, ConstraintSet.BOTTOM,
                0 // margin
            )
            connect(
                R.id.apps_fragment, ConstraintSet.BOTTOM,
                ConstraintSet.PARENT_ID, ConstraintSet.BOTTOM,
                0
            )
            constrainHeight(R.id.apps_fragment, ConstraintSet.MATCH_CONSTRAINT)
        }

        // 应用动画或直接更新布局
        if (animate) {
            TransitionManager.beginDelayedTransition(
                constraintLayout,
                ChangeBounds().apply {
                    duration = 300
                    interpolator = DecelerateInterpolator() // 替换为更平滑的插值器
                }
            )
            constraintSet.applyTo(constraintLayout)
        } else {
            constraintSet.applyTo(constraintLayout)
        }
    }

    fun updateLayoutPercentages(mode: Int) {
        when (mode) {
            1 -> { // 仅 vp_banner 改为 60%
                updateViewPercent(mBind.vpBanner, widthPercent = 0.6f)
            }
            2 -> { // 多视图调整
                updateViewPercent(mBind.vpBanner, widthPercent = 0.80f)
            }
            else -> { // 还原默认
                updateViewPercent(mBind.vpBanner, widthPercent = 0.5f)
            }
        }
    }

    private fun updateViewPercent(
        view: View,
        widthPercent: Float? = null,
        heightPercent: Float? = null
    ) {
        val params = view.layoutParams as ConstraintLayout.LayoutParams
        widthPercent?.let { params.matchConstraintPercentWidth = it }
        heightPercent?.let { params.matchConstraintPercentHeight = it }
        view.layoutParams = params
    }


    fun changeTextViewTopConstraint(
        useAlternate: Boolean,
        animate: Boolean = true,
        duration: Long = 300
    ) {
        // 1. 获取父容器 ConstraintLayout
        val constraintLayout = mBind.tvAppsBannerTitle.parent as? ConstraintLayout ?: run {
            return
        }

        // 2. 创建并克隆当前约束集
        val constraintSet = ConstraintSet().apply {
            clone(constraintLayout)

            // 3. 根据参数修改约束
            if (useAlternate) {
                // 切换到备用约束（示例：R.id.guideline_top_alternate）
                clear(R.id.tv_apps_banner_title, ConstraintSet.TOP)
                connect(
                    R.id.tv_apps_banner_title, ConstraintSet.TOP,
                    R.id.guideline_center_bannertext, ConstraintSet.TOP,
                    0
                )
            } else {
                // 还原默认约束（示例：R.id.guideline_top）
                clear(R.id.tv_apps_banner_title, ConstraintSet.TOP)
                connect(
                    R.id.tv_apps_banner_title, ConstraintSet.TOP,
                    R.id.guideline_top, ConstraintSet.TOP,
                    0
                )
            }
        }

        // 4. 处理动画逻辑
        if (animate) {
            TransitionManager.beginDelayedTransition(
                constraintLayout,
                ChangeBounds().apply {
                    this.duration = duration
                    interpolator = DecelerateInterpolator()
                }
            )
        }

        // 5. 应用约束变更
        constraintSet.applyTo(constraintLayout)
    }

    fun setListFragmentLittleHeight(animate: Boolean = true) {
        val constraintLayout = mBind.appsFragment.parent as ConstraintLayout


        val constraintSet = ConstraintSet().apply {
            clone(constraintLayout) // 克隆当前约束状态
            clear(R.id.apps_fragment, ConstraintSet.TOP) // 清除原有顶部约束
            connect(
                R.id.apps_fragment, ConstraintSet.TOP,
                R.id.guideline_b, ConstraintSet.BOTTOM,
                0 // margin
            )
            connect(
                R.id.apps_fragment, ConstraintSet.BOTTOM,
                ConstraintSet.PARENT_ID, ConstraintSet.BOTTOM,
                0
            )
            constrainHeight(R.id.apps_fragment, ConstraintSet.MATCH_CONSTRAINT)
        }

        // 应用动画或直接更新布局
        val transition = ChangeBounds().apply {
            duration = 300
            interpolator = DecelerateInterpolator()
        }
        if (animate) {
            TransitionManager.beginDelayedTransition(
                constraintLayout,
                transition
            )
            constraintSet.applyTo(constraintLayout)
        } else {
            constraintSet.applyTo(constraintLayout)
        }
    }



    companion object {

        @JvmStatic
        fun newInstance() =
            AppsAtvXintuFragment().apply {
                arguments = Bundle().apply {
                }
            }
    }
}
